// routes/house.js
const express = require('express');
const router = express.Router();
const { House, User, Category, Favorite } = require('../models');
const { Op } = require('sequelize');
const authMiddleware = require("../middlewares/auth");
// const { generateSignedUrl } = require('../middlewares/s3');
const jwt = require('jsonwebtoken');
const { getSignedUrl } = require("../utils/oss"); // 确保你已经正确引入签名工具

/**
 * @api {post} /addons/hicity/house/create 创建房产信息
 * @apiDescription 创建新的房产信息
 * @apiName CreateHouse
 * @apiGroup House
 * 
 * @apiParam {String} title 标题
 * @apiParam {String} content 房屋描述
 * @apiParam {Number} rent 租金/售价
 * @apiParam {Number} categoryId 分类ID
 * @apiParam {Number} room 室
 * @apiParam {Number} hall 厅
 * @apiParam {Number} loo 卫
 * @apiParam {Number} acreage 面积(平方米)
 * @apiParam {Number} [floor] 楼层
 * @apiParam {Number} [decoration] 装修程度: 1-毛坯, 2-简装, 3-精装
 * @apiParam {String} [towards] 朝向
 * @apiParam {Number} [type] 类型
 * @apiParam {Array} [houseconfig] 房屋配置，如家电家具等
 * @apiParam {Array} [banner_images] 房屋图片地址数组
 * @apiParam {Array} [labelconfig] 房屋标签配置
 * @apiParam {String} [person_name] 联系人姓名
 * @apiParam {String} [person_mobile] 联系人电话
 * @apiParam {String} info_type 信息类型: rent-出租, sell-出售, shop-商铺, ask-求租求购
 * @apiParam {Number} [is_top] 是否置顶: 0-否, 1-是
 */
router.post('/create', authMiddleware, async (req, res) => {
    try {
        const {
            title, content, rent, categoryId, room, hall, loo, acreage, floor, decoration,
            towards, type, houseconfig, banner_images, labelconfig, person_name, person_mobile,
            info_type, is_top
        } = req.body;

        const userId = req.userId;
        // 必填字段验证
        if (!title || !content || !rent || !categoryId || !room || !hall || !loo || !acreage || !info_type) {
            return res.status(400).json({
                code: 400,
                message: '缺少必要参数'
            });
        }

        // 验证info_type是否合法
        const validInfoTypes = ['rent', 'sell', 'shop', 'ask'];
        if (!validInfoTypes.includes(info_type)) {
            return res.status(400).json({
                code: 400,
                message: '无效的信息类型'
            });
        }

        // 创建房产信息
        const house = await House.create({
            title,
            content,
            rent,
            categoryId,
            userId,
            room,
            hall,
            loo,
            acreage,
            floor,
            decoration,
            towards,
            type,
            houseconfig,
            banner_images,
            labelconfig,
            person_name,
            person_mobile,
            info_type,
            is_top: is_top || 0,
            status: 1 // 默认上架
        });

        res.status(200).json({
            code: 200,
            message: '创建成功',
            data: house
        });
    } catch (error) {
        console.error('创建房产信息失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器错误'
        });
    }
});

/**
 * @api {get} /addons/hicity/house/list 房产信息列表
 * @apiDescription 获取房产信息列表
 * @apiName ListHouses
 * @apiGroup House
 * 
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [info_type] 信息类型: rent-出租, sell-出售, shop-商铺, ask-求租求购
 * @apiParam {Number} [categoryId] 分类ID
 * @apiParam {String} [userId=mine] 用户ID，mine表示当前用户
 * @apiParam {String} [keyword] 搜索关键词
 * @apiParam {Number} [min_acreage] 最小面积
 * @apiParam {Number} [max_acreage] 最大面积
 * @apiParam {Number} [min_rent] 最小租金/售价
 * @apiParam {Number} [max_rent] 最大租金/售价
 * @apiParam {Number} [decoration] 装修程度: 1-毛坯, 2-简装, 3-精装
 * @apiParam {Array} [lable_ids] 标签ID数组
 */
router.get('/list', async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const pageSize = parseInt(req.query.pageSize) || 10;
        const offset = (page - 1) * pageSize;

        // 构建查询条件
        const where = {};

        // 信息类型筛选
        if (req.query.info_type) {
            where.info_type = req.query.info_type;
        }

        // 分类筛选
        if (req.query.categoryId) {
            where.categoryId = req.query.categoryId;
        }

        // 用户筛选
        if (req.query.userId) {
            // 如果是'mine'，则获取当前用户的房产信息
            if (req.query.userId === 'mine') {
                try {
                    const token = req.headers.authorization?.split(' ')[1];
                    if (!token) {
                        return res.status(401).json({
                            code: 401,
                            message: '未授权'
                        });
                    }

                    const decoded = jwt.verify(token, process.env.JWT_SECRET);
                    where.userId = decoded.id;
                } catch (error) {
                    return res.status(401).json({
                        code: 401,
                        message: '未授权'
                    });
                }
            } else {
                where.userId = req.query.userId;
            }
        }

        // 关键词搜索
        if (req.query.keyword) {
            where[Op.or] = [
                { title: { [Op.like]: `%${req.query.keyword}%` } },
                { content: { [Op.like]: `%${req.query.keyword}%` } },
                { person_name: { [Op.like]: `%${req.query.keyword}%` } }
            ];
        }

        // 面积筛选
        if (req.query.min_acreage) {
            const minAcreage = parseFloat(req.query.min_acreage);
            if (!isNaN(minAcreage)) {
                where.acreage = { ...where.acreage, [Op.gte]: minAcreage };
            }
        }
        if (req.query.max_acreage) {
            const maxAcreage = parseFloat(req.query.max_acreage);
            if (!isNaN(maxAcreage)) {
                where.acreage = { ...where.acreage, [Op.lte]: maxAcreage };
            }
        }

        // 租金/售价筛选
        if (req.query.min_rent) {
            where.rent = { ...where.rent, [Op.gte]: parseFloat(req.query.min_rent) };
        }
        if (req.query.max_rent) {
            where.rent = { ...where.rent, [Op.lte]: parseFloat(req.query.max_rent) };
        }

        // 装修程度筛选
        if (req.query.decoration) {
            const decoration = parseInt(req.query.decoration);
            if (!isNaN(decoration)) {
                where.decoration = decoration;
            }
        }

        // 标签筛选 (复杂查询，需要在应用层面处理)
        const lable_ids = req.query.lable_ids ? JSON.parse(req.query.lable_ids) : null;

        // 查询房产信息
        const { count, rows } = await House.findAndCountAll({
            where,
            order: [
                ['is_top', 'DESC'],
                ['updatedAt', 'DESC']
            ],
            limit: pageSize,
            offset: offset,
            include: [
                // {
                //     model: User,
                //     as: 'author',
                //     attributes: ['id', 'username', 'avatar']
                // },
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        // 处理标签筛选
        let filteredRows = rows;
        if (lable_ids && lable_ids.length > 0) {
            filteredRows = rows.filter(house => {
                if (!house.labelconfig) return false;
                const houseLabelIds = house.labelconfig.map(label => label.id);
                return lable_ids.some(id => houseLabelIds.includes(parseInt(id)));
            });
        }

        // 处理图片URL
        const processedRows = await Promise.all(filteredRows.map(async (house) => {
            const houseObj = house.get({ plain: true });

            // 处理banner_images
            if (houseObj.banner_images && houseObj.banner_images.length > 0) {
                houseObj.signed_image_urls = await Promise.all(houseObj.banner_images.map(async (image) => {
                    if (typeof image === 'string') {
                        return getSignedUrl(image)
                    }
                    return getSignedUrl(image.path)
                }));
            }

            return houseObj;
        }));
        // const signedList = rows.map(item => {
        //     const data = item.toJSON();
        //     if (Array.isArray(data.banner_images)) {
        //         data.banner_images = data.image_urls.map(key => {
        //             try {
        //                 return getSignedUrl(key);
        //             } catch (err) {
        //                 console.error('[item] 生成签名失败:', key, err);
        //                 return null;
        //             }
        //         });
        //     } else {
        //         data.banner_images = [];
        //     }
        //     return data;
        // });

        res.json({
            code: 200,
            message: '获取成功',
            data: {
                total: lable_ids && lable_ids.length > 0 ? filteredRows.length : count,
                list: processedRows,
                page,
                pageSize
            }
        });
    } catch (error) {
        console.error('获取房产信息列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器错误'
        });
    }
});

/**
 * @api {get} /addons/hicity/house/main 房产信息详情
 * @apiDescription 获取房产信息详情
 * @apiName GetHouseDetail
 * @apiGroup House
 * 
 * @apiParam {Number} id 房产信息ID
 */
router.get('/main', async (req, res) => {
    try {
        const { id } = req.query;

        if (!id) {
            return res.status(400).json({
                code: 400,
                message: '缺少必要参数'
            });
        }

        // 查询房产信息
        const house = await House.findByPk(id, {
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        if (!house) {
            return res.status(404).json({
                code: 404,
                message: '房产信息不存在'
            });
        }

        // 转换为纯对象
        const houseObj = house.get({ plain: true });

        // 检查用户是否收藏了该房产信息
        let isFavorite = false;
        try {
            const token = req.headers.authorization?.split(' ')[1];
            if (token) {
                const decoded = jwt.verify(token, process.env.JWT_SECRET);
                const favorite = await Favorite.findOne({
                    where: {
                        userId: decoded.id,
                        itemId: id
                    }
                });
                isFavorite = !!favorite;
            }
        } catch (error) {
            // 忽略错误，默认为未收藏
        }

        // 处理banner_images
        if (houseObj.banner_images && houseObj.banner_images.length > 0) {
            houseObj.signed_image_urls = await Promise.all(houseObj.banner_images.map(async (image) => {
                if (typeof image === 'string') {
                    return getSignedUrl(image);
                }
                return getSignedUrl(image.path);
            }));
        }

        // 添加是否收藏字段
        houseObj.is_favorite = isFavorite;

        res.json({
            code: 200,
            message: '获取成功',
            data: houseObj
        });
    } catch (error) {
        console.error('获取房产信息详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器错误'
        });
    }
});

/**
 * @api {get} /addons/hicity/house/index 房产首页数据
 * @apiDescription 获取房产首页数据
 * @apiName GetHouseIndex
 * @apiGroup House
 */
router.get('/index', async (req, res) => {
    try {
        // 获取房屋出租列表
        const rent_list = await House.findAll({
            where: { info_type: 'rent', status: 1 },
            order: [
                ['is_top', 'DESC'],
                ['updatedAt', 'DESC']
            ],
            limit: 4,
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                },
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        // 获取房屋出售列表
        const sell_list = await House.findAll({
            where: { info_type: 'sell', status: 1 },
            order: [
                ['is_top', 'DESC'],
                ['updatedAt', 'DESC']
            ],
            limit: 4,
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                },
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        // 获取商铺出租列表
        const shop_list = await House.findAll({
            where: { info_type: 'shop', status: 1 },
            order: [
                ['is_top', 'DESC'],
                ['updatedAt', 'DESC']
            ],
            limit: 4,
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                },
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                }
            ]
        });

        // 处理图片URL
        // const processLists = async (list) => {
        //     return Promise.all(list.map(async (house) => {
        //         const houseObj = house.get({ plain: true });

        //         // 处理banner_images
        //         if (houseObj.banner_images && houseObj.banner_images.length > 0) {
        //             houseObj.banner_images = await Promise.all(houseObj.banner_images.map(async (image) => {
        //                 if (typeof image === 'string') {
        //                     return {
        //                         url: await generateSignedUrl(image),
        //                         path: image
        //                     };
        //                 }
        //                 return {
        //                     ...image,
        //                     url: await generateSignedUrl(image.path),
        //                 };
        //             }));
        //         }

        //         return houseObj;
        //     }));
        // };

        // const processedRentList = await processLists(rent_list);
        // const processedSellList = await processLists(sell_list);
        // const processedShopList = await processLists(shop_list);

        // 获取Banner
        const { Banner } = require('../models');
        const banner = await Banner.findOne({
            where: { position: 'house', isActive: true },
            order: [['sortOrder', 'ASC']]
        });

        res.json({
            code: 0,
            message: '获取成功',
            data: {
                rent_list: processedRentList,
                sell_list: processedSellList,
                shop_list: processedShopList,
                banner: banner
            }
        });
    } catch (error) {
        console.error('获取房产首页数据失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器错误'
        });
    }
});

module.exports = router;